package cn.micai.base.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/2/22 11:43
 */
public class AtomicUse {

    private static AtomicInteger count = new AtomicInteger(0);
    //多个addAndGet在一个方法内是非原子性的，需要加synchronized进行修饰，保证4个
    //addAndGet整体原子性
    public synchronized int multiAdd(){
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        count.addAndGet(1);
        count.addAndGet(2);
        count.addAndGet(3);
        count.addAndGet(4);//1+2+3+4=10，也就是说，执行一次multiAdd方法，count就加10
        return count.get();
    }

    public static void main(String[] args){
        final AtomicUse au = new AtomicUse();
        List<Thread> ts = new ArrayList<Thread>();
        for(int i=0;i<100;i++){
            ts.add(new Thread(new Runnable() {

                @Override
                public void run() {
                    System.out.println(au.multiAdd());
                }
            }));
        }
        for(Thread t:ts){
            t.start();
        }
    }
}
